<?php

/**
 * user controller, displays profiles, member list, logs in/out and registers
 * 
 * @author			wil hamilton <wil.hamilton@gmail.com>
 * @version 		0.2
 * @license			bsd
 * @todo			finish the index method
 */

 
class Controller extends controllerBase {

	#index page, displays member list, or single member profile
	public function index($userId = '')
	{
		include(MODULE_DIR . 'user/config.php');
		
		if($userId != '')
		{
			#show a specific user profile
			$query = new Query("SELECT * FROM `users` WHERE `id` = ?", $userId);
			
			if($query->num_rows() > 0)	//the user was found
			{
				#display profile information for the user
				$u = $query->fetch_assoc();
				$user= new user($u['id']);
				echo display::header($user->name);
			}
			else		//the user was not found
			{
				echo language_phrase::get('user-not-found');
			}
		}
		else
		{
			#show all users
			$query = new Query("SELECT * FROM `users` ORDER BY `id` DESC");
			
			$users = user::recordSet($query, 'user');
			
			foreach($users as $user)
			{
				echo '<li><a href="' . ROOT_URL . URL_BASE . $config['modules']['user']['base-url'] . $user->id . '">' . $user->name . '</a></li>';
			}
		}
	}
	
	
	#login page, lets users log in
	public function login($redir = '')
	{
		include(MODULE_DIR . 'user/config.php');
		
		#generate the login form
		$logged_in = false;	
		$errors = array();
		
		$this->title = language_phrase::get('login');
		
		if(user::isLoggedIn())
		{
			echo display::redirect(language_phrase::get('already-logged-in'));
		}
		else
		{
			if(isset($_POST['submit']))
			{
				//login form has been sent, process
				
				/* check email */
				if($_POST['email'] == '')
				{
					 $errors[] = 'missing-email';
				}
				else
				{
					
					$pLoginQuery = new Query("SELECT `id` FROM `users` WHERE `email` = ?", array($_POST['email']));
					
					if($pLoginQuery->num_rows() > 0)
					{
					
						while($login = $pLoginQuery->fetch_assoc())
						{
							$user = new user($login['id']);
						}
						
					}
					else
					{
						 $errors[] = 'invalid-user';
					}
					
				}
				
				/* check password */
				if($_POST['password'] == '')
				{
					 $errors[] = 'missing-password';
				}
				else
				{
					if($pLoginQuery->num_rows() > 0)
					{
						if($user->password !=  md5($user->salt . sha1($_POST['password'])))
						{
							//password is invalid
							$errors[] = 'wrong-password';
						}
					}
				}
				
				/* login  or display errors*/
				if(count($errors) <= 0)
				{
					//login and redirect
					
					$_SESSION['id'] = $user->id;
					$_SESSION['password'] = sha1($_POST['password']);
					$_SESSION['salt'] = $user->salt;
					unset($_POST);
					$logged_in = true;
					
				}
			}
			
			/* show login form */
			
			if($logged_in == true)
			{
				if($redir == 'admin')
					echo header("Location:  " . ROOT_URL . "admin");
				else
					echo header("Location:  " . ROOT_URL);
			}
			else
			{
				
				echo form::getForm('user_login', array($errors));
			}	
			
		}
	}
	
	#register page, lets new users register
	public function register()
	{
		include(MODULE_DIR . 'user/config.php');
		
		#set registration equal to false, and set up the errors array
		$registered = false;
		$errors = array();
		
		$this->title = language_phrase::get('register');
		
		if(user::isLoggedIn())
		{
			echo display::redirect(language_phrase::get('already-logged-in'));
		}
		else
		{
		
			if(isset($_POST['submit']))
			{
				//form has been sent; process
				
				$newUser = new user();
				
				
				// check for email validity 
				if (clean::checkEmail($_POST['email']))
				{
					//make sure they match
					if ($_POST['email'] === $_POST['confirmEmail'])
					{
						//check for usage
						$pEmailQuery = new Query("SELECT `id` FROM `users` WHERE `email` = ?", $_POST['email']);
						if($pEmailQuery->num_rows() > 0)
						{
							$errors[] = 'email-in-use';
						}
						else
						{
							$newUser->email = $_POST['email'];
						}
					}
					else
					{
						$errors[] = 'email-mismatch';
					}
				}
				else
				{
					$errors[] ='invalid-email';
				}
				
				if($_POST['username'] == '')
				{
					$errors[] = 'no-username';
				}
				else
				{
					$newUser->name = $_POST['username'];
				}
				
				// make sure user has a password 
				if (strlen($_POST['password']) > 5)
				{
					if ($_POST['password'] === $_POST['confirmPassword'])
					{
						$salt = substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, 16);
						$newUser->salt = $salt;
						$newUser->password = md5($salt . sha1($_POST['password']));
					}				
					else 
					{
						$errors []= 'password-mismatch';
					}
				}
				else
				{			
					$errors []= 'password-too-short';
				}
				
				
				// All required checks have been made, if everything is ok, add to DB, else; show errors 
				if(count($errors) == 0)
				{
					//there where no errors, save user, and redirect
					$newUser->group = 2;
					$newUser->save();
					
					$registered = true;
				}
				
			}
		
		
			// Show Registration Form 
			if($registered == true)
			{
				echo display::redirect(language_phrase::get('successful-registration'));
			}
			else
			{
				//echo form::registerForm($errors);
				echo form::getForm('user_register', array($errors));
			}
		}
	}
	
	
	#logout page, lets users logout
	# takes them back to the page they were viewing, if no page is set, takes them to the main page
	public function logout($currentPage = ROOT_URL)
	{
		#unset session info
		unset($_SESSION['id']);
		unset($_SESSION['password']);
		unset($_SESSION['salt']);
		
		#show redirect page
		echo display::redirect(language_phrase::get('logged-out'), $currentPage);
	}
	
	#send a user a new password
	public function resetPassword()
	{
		include(MODULE_DIR . 'user/config.php');
		
		
		
		$this->title = language_phrase::get('reset-password');
		$errors = array();
		$reset = false;
		
		if($_POST['submit'])
		{
			//the reset password form has been sent, process
			
			$query = new Query("SELECT * FROM `users` WHERE `email` = ?", $_POST['email']);
			
			if($query->num_rows() > 0)
			{
				//user was found
				$u = $query->fetch_assoc();
				
				$user = new user($u['id']);
				$tempPass = substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, 6);
				$salt = substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, 16);
				$user->salt = $salt;
				$user->password = md5($salt . sha1($tempPass));
				
				$user->save();
				
				#send email containing new password
				mail();
				
				$reset = true;
				
			}
			else
			{
				$errors[] = 'user-not-found';
			}
		
		}
		
		if($reset)
		{
			echo display::redirect(language_phrase::get('successful-reset'));
		}
		else
		{
			echo form::getForm('user_resetPassword', array($errors));
		}
	}
	
	public function changePassword()
	{
		
		
		if(($user = user::isLoggedIn()) == false)
		{
			echo display::redirect(language_phrase::get('not-logged-in'));
		}
		else
		{
			//$user = site::$user;
		
			$errors = array();
			$changed = false;
		
			if($_POST['submit'])
			{
				if($_POST['oldpassword'] == '')
				{
					 $errors[] = 'missing-password';
				}
				else
				{
					if($user->password !=  md5($user->salt . sha1($_POST['oldpassword'])))
					{
						//password is invalid
						$errors[] = 'wrong-password';
					}

				}
				
				
				// make sure user has a password 
				if (strlen($_POST['password']) > 5)
				{
					if ($_POST['password'] === $_POST['confirmPassword'])
					{
						$salt = substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, 16);
						$user->salt = $salt;
						$user->password = md5($salt . sha1($_POST['password']));
					}				
					else 
					{
						$errors []= 'password-mismatch';
					}
				}
				else
				{			
					$errors []= 'password-too-short';
				}
				
				if(count($errors) <= 0)
				{
					$user->save();
					
					$_SESSION['password'] = sha1($_POST['password']);
					$_SESSION['salt'] = $user->salt;
					$changed = true;
				}
			}
			
			if($changed)
			{
				echo 'password changed';
			}
			else
			{
				echo form::getForm('user_changePassword', array($errors));
			}
		}
	}
	
	public function edit()
	{
		echo "this is the edit user page";
	}
}
?>